package com.cloudcc.boot.service;

import com.cloudcc.boot.entity.mdm.wbs.CRM_WBS_DO;
import com.yangzg.cloudcc.openapi.exception.CloudccOpenApiException;
import com.yangzg.cloudcc.openapi.response.data.CloudccOpenApiUpsertResponse;
import com.yangzg.cloudcc.openapi.service.CloudccOpenApiService;
import com.yangzg.cloudcc.openapi.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class WbsToCrmService {

    private final CloudccOpenApiService cloudccOpenApiService;

    public WbsToCrmService(CloudccOpenApiService cloudccOpenApiService) {
        this.cloudccOpenApiService = cloudccOpenApiService;
    }

    public void insertOrUpdate(CRM_WBS_DO crmWbsDo) {
        String sql = String.format("select id from %s where is_deleted = '0' and code = '%s'", CRM_WBS_DO.OBJECT_API, crmWbsDo.getCode());
        List<CRM_WBS_DO> list = this.cloudccOpenApiService.cqlQueryDataList(sql, CRM_WBS_DO.class);
        CloudccOpenApiUpsertResponse response;
        if (list.isEmpty()) {
            // 插入
            response = this.cloudccOpenApiService.insertLt(Collections.singletonList(crmWbsDo), false);
        } else {
            // 更新
            CRM_WBS_DO exists = list.getFirst();
            crmWbsDo.setRecordId(exists.getRecordId());
            response = this.cloudccOpenApiService.updateLt(crmWbsDo);
        }
        if (!response.successfully() || !response.allSuccess()) {
            log.error("同步WBS数据失败:{}", JacksonUtils.toJsonString(response));
            throw new CloudccOpenApiException(response);
        }
    }

}
